package com.changgou.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName: AuthorizeFilter
 * @Auther: syq
 * @Date: 2021/7/8 16:09
 * @Version 1.0
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    private final String AUTHORIZATION_TOKEN ="Authorization";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        //判断访问登陆页面
        if(path.startsWith("/api/user/login")){
            return chain.filter(exchange);
        }
        String token = request.getQueryParams().getFirst(AUTHORIZATION_TOKEN);
        if(StringUtils.isEmpty(token)){
            token = request.getHeaders().getFirst(AUTHORIZATION_TOKEN);
        }
        if(StringUtils.isEmpty(token)){
            HttpCookie cookie = request.getCookies().getFirst(AUTHORIZATION_TOKEN);
            if(cookie != null){
                token = cookie.getValue();
            }
        }
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
